<template>
  <view class="content">
    <view style="width:300px ; height: 500px; border-radius: 15px; overflow: hidden;">
      <canvas :style="{ height: height + 'px', width: width + 'px' }" style="border-radius: 20rpx;" canvas-id="poster" id="poster"></canvas>
    </view>

    <view class="fotter-button" @click="myimg">保存图片</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      height: 500,
      width: 300,
      imgUrl: '',
      code: '',
      bgBanner: '',
      windowWidth: '',
      windowHeight: '',
      tempFilePath: [],
      recommendationCode: ' ', //推荐码
      niceName: '', //用户微信昵称
      nickPhoto: '', //用户微信头像
      headerwidth: '',
      headerheight: '',
      bigObj: ''
    };
  },

  onLoad() {
    uni.showToast({
      title: '加载中...',
      icon: 'loading'
    });
    this.getcode();
    const obj = uni.getStorageSync('userinfo');
    const userObj = uni.getStorageSync('userData');
    console.log('我是用户信息', userObj);
    this.niceName = userObj.nickName;
    // this.nickPhoto = userObj.avatarUrl
    console.log('我是用户信息=======>', this.niceName);
    console.log('我是用户信息===>', this.nickPhoto);
    this.recommendationCode = obj.recommendedCode;
    this.changeHeaderPhoto(obj.avatarUrl);
  },
  methods: {
    // 获取背景
    async getphoto() {
      const { data } = await uni.$http.get('/backGround/findBackGround');
      console.log(data);
      if (data.statusCode !== 200) {
        return;
      } else {
        this.imgUrl = data.data;
        const _this = this;
        // var ctx = uni.createCanvasContext('poster');
        // ctx.drawImage(_this.bgBanner, 0,0,_this.width,_this.height)
        // ctx.draw()
        uni.getImageInfo({
          src: _this.imgUrl,
          success(res) {
            console.log(res);
            // _this.height = res.height
            // _this.width = res.width
            console.log('海报背景:', res.path);
            _this.bgBanner = res.path;
            _this.getposter(_this.bgBanner);
          }
        });
      }
    },
    // 获取二维码
    getcode() {
      const _this = this;
      uni.request({
        url: uni.$http.baseUrl + '/wx/getQrCode?scene=' + uni.getStorageSync('openid'),
        method: 'GET',
        responseType: 'arraybuffer',
        header: {
          token: uni.getStorageSync('tokenValue')
        },
        success(res) {
          console.log('二维码呀呀呀呀呀', res);
          var base64 = wx.arrayBufferToBase64(res.data);
          var base64data = 'data:image/PNG;base64,' + base64;

          _this.changeBase(base64data);
          // _this.getphoto();
        }
      });
    },
    // 将base64文件处理成微信临时文件
    changeBase(base64data, FILE_BASE_NAME = 'tmp_base64src') {
      const _this = this;
      const fsm = uni.getFileSystemManager();
      return new Promise((resolve, reject) => {
        //format这个跟base64数据的开头对应
        const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
        if (!format) {
          reject(new Error('ERROR_BASE64SRC_PARSE'));
        }
        const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`;
        const buffer = wx.base64ToArrayBuffer(bodyData);
        fsm.writeFile({
          filePath,
          data: buffer,
          encoding: 'binary',
          success() {
            console.log('我事处理好得数据', filePath);
            _this.code = filePath;
            _this.getphoto();
            resolve(filePath);
          },
          fail() {
            reject(new Error('ERROR_BASE64SRC_WRITE'));
          }
        });
      });
    },

    // 将圆形头像变为临时路径
    changeHeaderPhoto(headerphoto) {
      const _this = this;
      uni
        .getImageInfo({
          src: headerphoto
        })
        .then(img => {
          console.log('imggggg' , img)
          if (img[1].errMsg == 'getImageInfo:ok') {
            let { width, height } = img[1];
            // _this.circleImage(img[1],width,height,20,35)

            _this.bigObj = img[1];
            _this.headerheight = height;
            _this.headerwidth = width;
            console.log('wowowowowwowowow', width);
            console.log('wowowowowwowowow', height);
          }
        });
    },

    circleImage(img, width, height, x, y) {
      console.log('popopopopopopo', img);
      let radius, diameter;
      //以最短的边为半径绘制圆
      if (width > height) {
        radius = height / 2;
      } else {
        radius = width / 2;
      }
      var ctx = uni.createCanvasContext('poster');
      diameter = radius * 2;
      ctx.beginPath();
      ctx.arc(x + radius, y + radius, radius, 0, Math.PI * 2, false);
      ctx.clip();
      console.log('我是裁剪头像', img.path);
      ctx.drawImage(img.path, x, y, diameter, diameter);
    },

    // 绘制canvas
    getposter(path) {
      var _this = this;
      uni.getSystemInfo({
        success(res) {
          //console.log('res===>', res);
          var windowWidth = res.windowWidth;
          var windowHeight = res.windowHeight;
          _this.windowWidth = "width:' " + windowWidth + "px';";
          _this.windowHeight = "height:' " + windowHeight + "px';";
          var ctx = uni.createCanvasContext('poster');
          var path1 = path;
          var path2 = _this.code;
          var path3 = _this.nickPhoto;
          var font1 = _this.recommendationCode;
          var font2 = _this.niceName;

          // console.log('海报底部背景图11' + path1);
          // console.log('海报底部背景图22' + path2);
          ctx.drawImage(path1, 0, 0, _this.width, _this.height);
          ctx.drawImage(path2, 90, 325, 120, 120);

          // ctx.beginPath()

          ctx.setFillStyle('#FFFFFF');
          ctx.setFontSize(13);
          ctx.fillText(font2, 75, 45);

          ctx.setFillStyle('#FFFFFF');
          ctx.setFontSize(10);
          ctx.fillText('邀请您加入', 75, 60);

          ctx.setFillStyle('#000000');
          ctx.setFontSize(12);
          ctx.fillText(font1, 170, 470);

          const avatarWidth = 50;

          const w = 40;
          const h = 40;
          const x = 25;
          const y = 25;
          const obj = _this.bigObj;

          let radius, diameter;
          if (w > h) {
            radius = h / 2;
          } else {
            radius = w / 2;
          }
          diameter = radius * 2;
          ctx.beginPath();
          ctx.arc(x + radius, y + radius, radius, 0, Math.PI * 2, false);
          ctx.clip();
          console.log('我是裁剪头像', obj.path);
          ctx.drawImage(obj.path, x, y, diameter, diameter);

          ctx.draw(false, () => {
            setTimeout(  () => {
              uni.canvasToTempFilePath({ 
              							canvasId: 'poster',
              							destWidth: _this.width*2, //分享图片尺寸=画布尺寸1*缩放比0.5*像素比2
              							destHeight: _this.height*2,
              							quality:1,
              							fileType:'jpg',
              							success: (res) => {
              								// console.log(res,'success')
              								uni.compressImage({
              									src: res.tempFilePath,
              									quality: 100,
              									success: res => {
                                  console.log('wowowwowowo===>' , res)
              										const share_img=res.tempFilePath
              										uni.canvasToTempFilePath({
              											canvasId: 'poster',
              											destWidth: _this.cropW*2,   //展示图片尺寸=画布尺寸1*像素比2
              											destHeight: _this.cropH*2,
              											quality:1,
              											fileType:'jpg',
              											success: (res) => {
              												console.log(res.tempFilePath);
              												uni.setStorageSync('imgs',res.tempFilePath)
              												uni.hideLoading()
              												const img = res.tempFilePath
              											
              											},
              										}, _this);
              									}
              								})
              							},
              						}, _this);
             
            },500)
          });
        }
      });
    },

    myimg() {
      uni.saveImageToPhotosAlbum({
        filePath: uni.getStorageSync('imgs'),
        success: function() {
          uni.showToast({
            icon: 'none',
            position: 'bottom',
            title: '海报已下载,请分享!' // res.tempFilePath
          });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.content {
  width: 100%;
  // height: 100%;
  padding-top: 30px;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;

  .fotter-button {
    margin-top: 20rpx;
    width: 50%;
    height: 80rpx;
    box-sizing: border-box;
    background-color: #f2bd57;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #ffffff;
    font-size: 28rpx;
    border-radius: 10rpx;
  }
}
</style>
